<template>
  <view class="content">
    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <uni-load-more status="loading" :content-text="loadingText"></uni-load-more>
    </view>
    
    <!-- 内容区域 -->
    <view v-else>
      <view class="picture-outer"
			 v-for="(item, index) in pictureList" 
			:key="index"
			 @click="navigateTo(item.content_id)">
        <view class="image-section">
          <!-- 图片 -->
          <image 
            :src="item.hp_img_url" 
            mode="aspectFill" 
            @load="onImageLoad" 
            @error="onImageError"
            :class="{'image-loading': imageLoading[index]}"
						:data-index="index"
          ></image>
          <view class="image-placeholder" v-if="imageLoading[index] || imageError[index]">
            <text>加载中...</text>
          </view>
        </view>
        
        <!-- 标题 -->
        <view class="title-section">
          <text class="title">{{ item.hp_title }}</text>
          <text class="author">作者：{{ item.hp_author }}</text>
        </view>
        
        <!-- 描述 -->
        <view class="description">{{ item.hp_content }}</view>
        
        <!-- 底部信息 -->
        <view class="footer">{{ formatDate(item.hp_makettime) }}</view>
      </view>
      
      <!-- 加载更多 -->
      <uni-load-more :status="loadMoreStatus" v-if="pictureList.length > 0"></uni-load-more>
    </view>
  </view>
</template>

<script setup>
import { onLoad, onReachBottom } from '@dcloudio/uni-app';
import { ref } from 'vue';
import { requestData } from '../../utils/request';

// 所有图文详情的数组列表
const pictureList = ref([]);
const loading = ref(true);
const loadMoreStatus = ref('more');
const imageLoading = ref([]);
const imageError = ref([]);
const loadingText = {
  contentdown: '上拉显示更多',
  contentrefresh: '加载中',
  contentnomore: '没有更多数据了'
};

// 根据图文集id加载图文集详细内容
async function getImageDetail(id) {
  try {
    const resData = await requestData({ url: '/api/hp/detail/' + id });
    console.log(resData.data, ' 图文集详细内容');
    pictureList.value.push(resData.data);
    
    // 初始化图片加载状态
    imageLoading.value[pictureList.value.length - 1] = true;
    imageError.value[pictureList.value.length - 1] = false;
  } catch (error) {
    console.error('获取图文详情失败:', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    });
  }
}

// 获取首页推荐图文集id列表
async function getIdList() {
  try {
    let result = await requestData({ url: '/api/hp/idlist/0' });
    console.log(result.data, 'pppppppp');
    
    // 限制一次加载的数量，避免一次性请求过多
    const batchSize = 5;
    const batchCount = Math.ceil(result.data.length / batchSize);
    
    for (let i = 0; i < batchCount; i++) {
      const batch = result.data.slice(i * batchSize, (i + 1) * batchSize);
      await Promise.all(batch.map(pid => getImageDetail(pid)));
      
      // 每批加载后添加延迟，避免请求过于频繁
      if (i < batchCount - 1) {
        await new Promise(resolve => setTimeout(resolve, 300));
      }
    }
    
    loading.value = false;
  } catch (error) {
    console.error('获取ID列表失败:', error);
    loading.value = false;
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    });
  }
}

// 图片加载完成
function onImageLoad(e) {
  const index = e.currentTarget.dataset.index;
  imageLoading.value[index] = false;
}

// 图片加载失败
function onImageError(e) {
  const index = e.currentTarget.dataset.index;
  imageLoading.value[index] = false;
  imageError.value[index] = true;
}

// 格式化日期
function formatDate(dateStr) {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}

// 页面加载
onLoad(() => {
  console.log('页面初次加载');
  getIdList();
});

// 触底加载更多
onReachBottom(() => {
  if (loadMoreStatus.value === 'noMore') return;
  loadMoreStatus.value = 'loading';
  
  setTimeout(() => {
    loadMoreStatus.value = 'noMore';
  }, 1000);
});
// function navigateTo(cpid) {
//   uni.navigateTo({
//     url: `/pages/detail/detail?pid=${cpid}`
//   });
// }

</script>

<style lang="scss">
@import '@/pages/style/picture.scss'
</style>
